package com.sali.exception;




import com.sali.enums.ValidatorEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(value = BindException.class)
    public ErrorHandlerResult handleValidException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<String,Object> map = new HashMap<>();
        if (bindingResult.hasErrors()) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
        }
        return ErrorHandlerResult.fail(ValidatorEnum.PARAMATER_ERROR.getCode(), map,e);
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ErrorHandlerResult handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<String,Object> map = new HashMap<>();
        if (bindingResult.hasErrors()) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            if (fieldErrors.size() > 0) {
                for (FieldError fieldError : fieldErrors) {
                    map.put(fieldError.getField(), fieldError.getDefaultMessage());
                }
            }
        }
        return ErrorHandlerResult.fail(ValidatorEnum.PARAMATER_ERROR.getCode(), map,e);
    }

}
